package com.supertange.miniapp.wepet.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.processing.OperationStatus;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.*;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.supertange.miniapp.wepet.common.vo.AjaxResult;

/**
 * @author DinMaster
 * @Title: 七牛云工具类封装
 * @date 2018/8/3013:30
 */
public class QnUtil {

    public static Auth auth = null;
    //定义变量
    public static UploadManager uploadManager;
    public static OperationManager operationManager;
    public static BucketManager bucketManager;
    public static String accesskey;
    public static String secretkey;
    public static Configuration cfg;
    // 令牌验证
    public static String token;

    //初始化配置
    public QnUtil create(String accesskey, String secretkey) {
        //授权验证
        auth = Auth.create(accesskey, secretkey);
        //华东    Zone.zone0()
        //华北    Zone.zone1()
        //华南    Zone.zone2()
        //北美    Zone.zoneNa0()
        cfg = new Configuration(Zone.zone2());
        return this;
    }

    /**
     * 获取上传管理器
     *
     * @param bucket
     * @return
     */
    public void setUploadManager(String bucket) {
        uploadManager = new UploadManager(cfg);
    }

    /**
     * 获取Bucket的管理对象
     *
     * @return
     */
    public BucketManager getBucketManager() {
        bucketManager = new BucketManager(auth, cfg);
        return bucketManager;
    }

    /**
     * 获取上传管理器
     *
     * @param bucket
     * @return
     */
    public void setOperationManager(String bucket) {
        operationManager = new OperationManager(auth, cfg);
    }

    /**
     * 获取Bucket的管理对象
     *
     * @return
     */
    public OperationManager getOperationManagerr() {
        operationManager = new OperationManager(auth, cfg);
        return operationManager;
    }

    /**
     * 获取七牛云的上传Token,设置callbackUrl以及callbackBody,七牛将文件名和文件大小回调给业务服务器
     *
     * @param bucket
     * @return
     */
    public String getToken(String bucket, String callbackUrl) {
        return auth.uploadToken(bucket, null, 3600, new StringMap()
//                .put("callbackUrl",callbackUrl)
                .put("callbackBody", "key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)filename=$(fname)"));
    }

    /**
     * 不覆盖上传
     *
     * @param bucket      空间名字
     * @param callbackUrl 回调链接
     * @param key         文件名称
     */
    public String uploadFile(String bucket, String callbackUrl, final byte[] data, final String key) {
        DefaultPutRet putRet = null;
        String result = null;
        try {
            token = getToken(bucket, callbackUrl);
            Response response = uploadManager.put(data, key, token, null, null, false);
            //解析上传成功的结果
            result = response.bodyString();
//            putRet = new Gson().fromJson(, DefaultPutRet.class);
            if (response.statusCode != 200) {
                throw new MyException("上传失败");
            }
        } catch (QiniuException e) {
            Response r = e.response;
            throw new MyException(r.error);
        }
        return result;
    }

//    /**
//     * 覆盖上传
//     * 遇见同名的文件进行 覆盖
//     */
//    public static void uploadCoverFile(String bucket, String filePath, String key) {
//        try {
//            token = auth.uploadToken(bucket, key, 6600, new StringMap().put("insertOnly", 0));
//            Response response = uploadManager.put(filePath, key, token);
//            if (response.statusCode == 200) {
//                System.out.println("图片上传成功...");
//            }
//        } catch (QiniuException e) {
//            Response r = e.response;
//            System.out.println(r.toString());
//            e.printStackTrace();
//        }
//    }

    /**
     * 根据空间名和文件key 删除某空间的文件
     *
     * @param bucket
     * @param key
     */
    public AjaxResult delBucketKey(String bucket, String key) {
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException e) {
            Response r = e.response;
            throw new MyException(r.error);
        }
        return AjaxResult.ok();
    }

    /**
     * 删除多个文件
     *
     * @param bucket bucket的名称
     * @param keys   文件名称数组
     * @return
     */
    public AjaxResult deletes(String bucket, String[] keys) {
        try {
            //当文件大于1000的时候，就直接不处理
            if (keys.length > 1000) {
                throw new MyException("删除失败");
            }

            //设定删除的数据
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, keys);
            BucketManager bucketManager = getBucketManager();
            //发送请求
            Response response = bucketManager.batch(batchOperations);

            //返回数据
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < keys.length; i++) {
                BatchStatus status = batchStatusList[i];
                if (status.code != 200) {
                    throw new MyException(status.data.error);
                }
            }
        } catch (Exception e) {
            throw new MyException("删除失败");
        }
        return AjaxResult.ok();
    }

    /**
     * 根据条件获取文件
     *
     * @param bucket    空间
     * @param prefix    文件前缀
     * @param limit     文件限制数
     * @param delimiter 目录结构
     * @return
     */
    public FileInfo[] getFileInfos(String bucket, String prefix, int limit, String delimiter) {
        FileListing fileListing = null;
        try {
            BucketManager bucketManager = getBucketManager();
            //列举空间文件列表
            fileListing = bucketManager.listFiles(bucket, prefix, null, limit, delimiter);

        } catch (Exception e) {
            throw new MyException("查找文件失败");
        }
        return fileListing.items;
    }

    /**
     * 获取单个文件信息
     */
    public FileInfo getFileInfo(String bucket, String fileKey) {
        BucketManager bucketManager = getBucketManager();
        FileInfo info = null;
        //列举空间文件列表
        try {
            info = bucketManager.stat(bucket, fileKey);
        } catch (QiniuException e) {
            throw new MyException("查找文件失败");
        }
        return info;
    }

    /**
     * 获取视频封面
     *
     * @param fromBucket 要转码的空间
     * @param key        要转码的key
     * @throws QiniuException
     */
    public String getVideoCover(String fromBucket, String key, String toCoverPath) {
        OperationManager operationManager = getOperationManagerr();
        //设置转码的队列
        String pipeline = "wepet_patch_cover";
        // 设置转码操作参数
        String urlbase64 = UrlSafeBase64.encodeToString(fromBucket + ":" + toCoverPath);
        String VIDEO_FOPS = "vframe/jpg/offset/1" + "|saveas/" + urlbase64;
        //封面图的路径
        String coverPath = "";
        //持久化id
        String persistentId = "";
        //设置pipeline参数
        StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
        try {
            persistentId = operationManager.pfop(fromBucket, key, VIDEO_FOPS, params);
            //            OperationStatus operStatus = operationManager.prefop(persistentId);
        } catch (QiniuException e) {
            throw new RuntimeException((e.getCause()));
        }
        coverPath = toCoverPath;
        return coverPath;
    }

    /**
     * 视频加水印
     *
     * @param fromBucket 要转码的空间
     * @param key        要转码的key
     * @throws QiniuException
     */
    public String qnVideoAddImageWater(String fromBucket, String key, String toWaterVideoPath, String waterBase64Image) {
        OperationManager operationManager = getOperationManagerr();
        //设置转码的队列
        String pipeline = "wepet_video_addWater";
        // 设置转码操作参数
        String urlbase64 = UrlSafeBase64.encodeToString(fromBucket + ":" + toWaterVideoPath);
        String VIDEO_FOPS = "avthumb/mp4/wmImage/" + waterBase64Image + "/wmGravity/NorthWest/wmOffsetY/-10/wmOffsetY/-10/wmFontSize/20" + "|saveas/" + urlbase64;
        //封面图的路径
        String wateredVideoPath = "";
        //持久化id
        String persistentId = "";
        //设置pipeline参数
        StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
        try {
            persistentId = operationManager.pfop(fromBucket, key, VIDEO_FOPS, params);
//            OperationStatus operStatus = operationManager.prefop(persistentId);
        } catch (QiniuException e) {
            throw new RuntimeException((e.getCause()));
        }
        wateredVideoPath = toWaterVideoPath;
        return wateredVideoPath;
    }

//    /**
//     * 下载
//      * @param url
//     * @param key
//     */
//    public String download(String url,String key){
//        //构造私有空间的需要生成的下载的链接
//        //调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
//        String downloadRUL = auth.privateDownloadUrl(url+key‬,3600);
//        Assert.notNull(downloadRUL,"未生成下载链接");
//        return downloadRUL;
//    }
}
